package com.tx.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tx.entity.Page;
import com.tx.entity.User;
import com.tx.service.UserService;
import com.tx.utils.FileUtil;
import com.tx.utils.ImageUrl;
import com.tx.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller("userController")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 跳转到登录页面
     * */
    @RequestMapping("/to_login")
    private String loginPage(){
        return  "/login";
    }
    /**
     * 用户登录校验
     * */
    @RequestMapping("/login")
    public String login(@RequestParam String userName,
                        @RequestParam String uPassword,
                        HttpSession session){
        User user = userService.getUser(userName,uPassword);
        if(user!=null){//用户名密码正确
            user.setuPassword(null);//不将密码传入页面
            session.setAttribute("user",user);
            session.removeAttribute("msg");
            if(user.getuType().equals("admin")){
                return "redirect:/admin/index.do";
            }
            return "redirect:/blog/index.do";
        }else{
            session.setAttribute("msg","用户名或密码错误");
            return "redirect:/user/to_login.do";//重定向
        }
    }
    /**
     * 退出登录
     * */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");//清空session的内容
        return "redirect:/blog/index.do";
    }
    /**
     * 打开注册界面
     * */
    @RequestMapping("/to_register")
    public String registerPage(){
        return "/register";
    }
    /**
     * 打开邮箱登录界面
     * */
    @RequestMapping("/to_loginEmail")
    public String loginEmai(){
        return "/login_email";
    }
    /**
     * 打开忘记密码界面
     * */
    @RequestMapping("/to_forget")
    public String forget(){
        return "/forget";
    }
    /**
     * 用户邮箱登录
     */
    @RequestMapping("/loginEmail")
    public String loginEmail(HttpServletRequest request,HttpSession session){
        String   uEmail = request.getParameter("email");
        User user = userService.getUserByEmail(uEmail);
        user.setuPassword(null);//不将密码传入页面
        session.setAttribute("user",user);
        session.removeAttribute("msg");
        return "redirect:/blog/index.do";
    }
    /**
     * 用户注册
     * */
    @RequestMapping("/register")
    public String register(HttpSession session,User user){
        //设置用户默认头像
        user.setuImage(ImageUrl.uImage);
        userService.add(user);//调用业务层方法添加用户
        return "redirect:/user/to_login.do";//重定向到登录界面
    }
    /**
     * 用户注册:验证用户名是否存在
     * */
    @RequestMapping("/checkUserName")
    @ResponseBody
    public Integer checkUserName(@RequestParam String username){
       // System.out.println("checkUserName方法===================");
        //查询数据库中是否有用户名相同的用户
        User user1 = userService.getUserByName(username);
        if (user1!=null){
           //用户名已存在
            return 0;//
        }else{
            //用户名不存在，可以注册，返回1
            return 1;
        }

    }
    /**
     * 用户注册:验证用户邮箱是否存在
     * */
    @RequestMapping("/checkUserEmail")
    @ResponseBody
    public Integer checkEmail(@RequestParam String email){
       // System.out.println("checkEmail方法==================="+email);
        //查询数据库中是否有邮箱相同的用户
        User user = userService.getUserByEmail(email);

        if (user!=null){
            //邮箱已存在
            //System.out.println("返回结果0");
            return 0;//
        }else{
            //邮箱不存在，可以注册，返回1
            //System.out.println("返回结果1");
            return 1;
        }

    }

    //发送验证码邮件
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    @ResponseBody
    public String sendCode( @RequestParam String email,@RequestParam int flag) {
        //发送邮件
        String codeStr = userService.sendEmail(email,flag);
        //将存在的大写字母转化为小写再将验证码进行加密
        String code = StringUtil.encode(codeStr.toLowerCase());
        System.out.println("uc-code"+code);
        //返回给页面
        return code;
    }
    //判断验证码是否填写正确
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    @ResponseBody
    public Integer checkCode( @RequestParam String emailcode, @RequestParam String hiddencode) {

        //将验证码大写字母转化为小写进行加密
        String code = StringUtil.encode(emailcode.toLowerCase());
        if (code.equals(hiddencode)){//相等
            return 1;
        }else{//不相等
            return 0;
        }
    }
    /**
     * 打开注册界面
     * */
    @RequestMapping("/quanxian")
    public String quanxain(Map<String,Object> map){
        map.put("user",new User());
        return "/quanxian";
    }
    /* *
     * @description:  用户头像上传
     * @author tcx
     * @date 2019/11/15
     * @param file
     * @param session
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @ResponseBody
    @RequestMapping(value = "/student/uploadHeadImg", method = RequestMethod.POST)
    public Map<String,Object> uploadHead(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {

        //获取文件名
        String fileName = file.getOriginalFilename();
        //截取扩展名
        String extName = fileName.substring(fileName.lastIndexOf("."));
        List list = new ArrayList();
        list.add(".jpg");
        list.add(".png");
        list.add(".jpeg");
        list.add(".gif");
        Map map = new HashMap<String,Object>();
       // System.out.println("===========uploadHeadImg=============");
        if(list.contains(extName.toLowerCase())){

            String originalFileName = file.getOriginalFilename();
            //获取项目根路径
            String fileUrl = "/";
            fileUrl = session.getServletContext().getRealPath(fileUrl);
            /* System.out.println("fileUrl = " + fileUrl);*/
            //向url地址存储文件
            String url = FileUtil.uploadHeadImage(file, fileUrl,originalFileName);
            //向数据库上传头像
            //System.out.println("url====="+url);
            //从session中拿到用户id
            User user = (User) session.getAttribute("user");
            user.setuImage(url);
            session.removeAttribute("user");
            session.setAttribute("user",userService.editHeadImage(user));
            //System.out.println("url:"+url);;
            //返回json
            map.put("msg","ok");
            map.put("code",200);
            Map<String,Object> map2=new HashMap<>();
            map.put("data",map2);
            map2.put("src",url);
        }else {
            map.put("msg","error");
            map.put("code",0);
        }
        return map;
    }
    /* *
     * @description:  删除用户
     * @author tcx
     * @date 2019/12/20
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/teacher/remove")
    public String remove(HttpServletRequest request){
        Integer uId = Integer.parseInt(request.getParameter("uId"));
        userService.remove(uId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg", 200);
        Gson gson = new Gson();
        return  gson.toJson(map);
    }
    //修改昵称
    @RequestMapping("/student/updateNickName")
    public String updateNickName(HttpSession session,User user){
        userService.editNickName(user);
        //System.out.println(user.getuNickName()+"==="+user.getuId());
        session.removeAttribute("user");
        session.setAttribute("user",userService.get(user.getuId()));
        return "redirect:/blog/student/to_studentSet.do";
    }
    //修改密码
    @RequestMapping("/student/editpwd")
    public String updatePwd(User user){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uId", user.getuId());//设置uId
        map.put("uPassword", user.getuPassword());//设置uPwd
        userService.editPwd(map);
        return "redirect:/user/logout.do";
    }
    //忘记密码
    @RequestMapping("/student/updatepwd")
    @ResponseBody
    public String updatePwd(@RequestParam(value = "uId", required = false) Integer uId,
                            @RequestParam(value = "uEmail", required = false) String uEmail,
                            @RequestParam(value = "uPwd", required = false) String uPwd,HttpSession session){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uId", uId);//设置uId
        map.put("uEmail",uEmail);//设置uEmail
        map.put("uPassword", uPwd);//设置uPwd
        System.out.println("uId="+uId);
        System.out.println("uEmail="+uEmail);
        System.out.println("uPassword="+uPwd);
       int flag= userService.editPwd(map);
        Gson gson = new Gson();
        if (flag > 0) {
            session.removeAttribute("user");
            map.put("code",0);
            map.put("msg","修改成功");
        } else {
            map.put("code",-1);
            map.put("msg","修改失败");
        }
        return gson.toJson(map);
    }
}
